/*
 * @Author: szx
 * @Date: 2021-12-03 10:45:19
 * @LastEditTime: 2022-03-09 16:23:21
 * @Description:
 * @FilePath: \leetcode\1000-1099\1005\1005.js
 */
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var largestSumAfterKNegations = function (nums, k) {
    nums.sort((a, b) => {
        return Math.abs(b) - Math.abs(a);
    });
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] < 0 && k > 0) {
            nums[i] *= -1;
            k--;
        }
    }

    if (k > 0 && k % 2 === 1) {
        nums[nums.length - 1] *= -1;
    }

    return nums.reduce((a, b) => {
        return a + b;
    });
};
